package com.base.system.base.db.specifications;

import cn.hutool.core.util.StrUtil;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.From;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Root;
import java.io.Serializable;

abstract class AbstractSpecification<T> implements Specification<T>, Serializable {
    private static final long serialVersionUID = 1L;

    JoinType joinType = JoinType.INNER; //默认是INNER

    /**
     * 获取需要查询的属性
     */
    String getProperty(String property) {
        if (property.contains(".")) {
            String[] propertyAttr = StrUtil.split(property, ".");
            return propertyAttr[propertyAttr.length - 1];
        }
        return property;
    }

    /**
     * 获取Path，需要对比的字段的From
     */
    From getFrom(String property, Root root) {
        From from = root;
        if (property.contains(".")) {
            String[] propertyAttr = StrUtil.split(property, ".");
            for (int i = 0; i < propertyAttr.length - 1; i++) from = from.join(propertyAttr[i], joinType);
        }
        return from;
    }
}
